from PyQt5.QtWidgets import (
    QWidget, QListWidget, QVBoxLayout, QLabel,
    QMenu, QAction, QMessageBox
)
from PyQt5.QtCore import Qt, QPoint
from core.schedule_manager import ScheduleService
from database.db_session import get_db


class ScheduleListWidget(QWidget):
    def __init__(self):
        super().__init__()
        # 一个字典，用于存储日程对象与列表项文本的映射关系。
        self.schedule_map = {}

        layout = QVBoxLayout()
        self.label = QLabel("日程列表")
        self.list_widget = QListWidget()

        # 设置QListWidget的上下文菜单策略为自定义上下文菜单。用于右键显示菜单。
        self.list_widget.setContextMenuPolicy(Qt.CustomContextMenu)
        self.list_widget.customContextMenuRequested.connect(self.show_context_menu)

        # 绑定点击事件
        self.list_widget.itemClicked.connect(self.show_detail_dialog)

        layout.addWidget(self.label)
        layout.addWidget(self.list_widget)
        self.setLayout(layout)

        self.setStyleSheet("""
                QLabel{
                    font-family: "微软雅黑";
                    font-size: 10pt;
                    color: #1a1a1a;
                }
                QListWidget {
                    background: white;
                    border-radius: 6px;
                    padding: 10px;
                    font-size: 25px;
                    color: #333;
                }
                QListWidget::item {
                    background: #f8f8f8;
                    margin: 8px 0;
                    padding: 10px;
                    border-radius: 8px;
                    border: 1px solid #ccc;
                }
                QListWidget::item:hover {
                    background: #e6f7ff;
                }
                QListWidget::item:selected {
                    background: #cceeff;
                    border: 1px solid #4CAF50;
                }
        """)

    def load_schedules(self, schedules):
        self.list_widget.clear()
        self.schedule_map.clear()

        for s in schedules:
            title = s.title
            start_time = s.start_time.strftime("%Y-%m-%d %H:%M") if s.start_time else "-"
            end_time = s.end_time.strftime("%Y-%m-%d %H:%M") if s.end_time else "-"
            reminder = s.reminder_at.strftime("%Y-%m-%d %H:%M") if s.reminder_at else "无提醒"

            item_text = (
                f"{title}\n"
                f"⏰ 开始时间: {start_time}    结束时间: {end_time}\n"
                f"🔔 提醒时间: {reminder}"
            )

            self.list_widget.addItem(item_text)
            self.schedule_map[item_text] = s

    def show_context_menu(self, point: QPoint):
        # 获取鼠标点击位置的列表项。
        item = self.list_widget.itemAt(point)
        if not item:
            return

        # 创建右键菜单，添加删除操作
        menu = QMenu(self)
        delete_action = QAction("删除日程", self)
        delete_action.triggered.connect(lambda: self.delete_schedule(item.text()))
        menu.addAction(delete_action)
        menu.exec_(self.list_widget.mapToGlobal(point))

    def delete_schedule(self, item_text):
        schedule = self.schedule_map.get(item_text)
        if not schedule:
            return

        reply = QMessageBox.question(
            self, "确认删除", f"确定要删除日程：{schedule.title}？",
            QMessageBox.Yes | QMessageBox.No
        )
        if reply == QMessageBox.Yes:
            try:
                db = next(get_db())
                success = ScheduleService.delete_schedule(db, schedule.id)
            finally:
                db.close()  # 确保会话关闭
            if success:
                QMessageBox.information(self, "删除成功", "请点击“刷新”按钮以更新列表。")
            else:
                QMessageBox.warning(self, "删除失败", "操作失败，请稍后重试。")

    def show_detail_dialog(self, item):
        from ui.schedule_detail_dialog import ScheduleDetailDialog
        schedule = self.schedule_map.get(item.text())
        if schedule:
            dialog = ScheduleDetailDialog(schedule, self)
            dialog.exec_()
